package com.hzhc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzhc.entity.CntrInfo;
import com.hzhc.entity.DpMapData;
import com.hzhc.entity.TrainPlan;
import com.hzhc.entity.TrainPlanDetail;
import com.hzhc.mapper.CntrInfoMapper;
import com.hzhc.mapper.DpMapDataMapper;
import com.hzhc.mapper.TrainPlanDetailMapper;
import com.hzhc.mapper.TrainPlanMapper;
import com.hzhc.service.DpMapDataService;
import com.hzhc.utils.BeanUtils;
import com.hzhc.utils.StringUtils;
import com.hzhc.vo.TrainPlanDetailVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 大屏数据表 服务实现类
 * </p>
 *
 * @author 功不唐捐
 * @since 2024-09-25
 */
@Service
@RequiredArgsConstructor
public class DpMapDataServiceImpl extends ServiceImpl<DpMapDataMapper, DpMapData> implements DpMapDataService {
    private final TrainPlanMapper trainPlanMapper;
    private final TrainPlanDetailMapper trainPlanDetailMapper;
    private final CntrInfoMapper cntrInfoMapper;

    @Override
    public void updateFinishTotal() {
        TrainPlanDetailVo vo=new TrainPlanDetailVo();
        // 获取当前年份的第一天和最后一天
        // 获取当前年份
        int currentYear = Year.now().getValue();
        // 获取当前年份的第一天（1月1日）
        LocalDate firstDayOfYear = LocalDate.of(currentYear, 1, 1);
        // 获取当前年份的最后一天（12月31日）
        // 方法一：直接指定
        LocalDate lastDayOfYear = LocalDate.of(currentYear, 12, 31);

        //上一年 集装箱吞吐量查询
        LocalDate formerStartYear = LocalDate.of(currentYear, 1, 1);
        LocalDate forEndYear = LocalDate.of(currentYear, 12, 31);

        // 转换为 LocalDateTime，因为假设 zx_time 是 LocalDateTime 类型
        LocalDateTime startDateTime = LocalDateTime.parse(firstDayOfYear+" 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime endDateTime = LocalDateTime.parse(lastDayOfYear+" 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime formerStartDateTime = LocalDateTime.parse(formerStartYear+" 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime formerEndDateTime = LocalDateTime.parse(forEndYear+" 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        Integer yearSum=0;
        Integer monthSum=0;
        Integer quarterSum=0;
        Integer weekSum=0;
        Integer daySum=0;

        List<DpMapData> dpMapData = baseMapper.selectList(new QueryWrapper<DpMapData>().eq("select_type", "完成量"));
        List<DpMapData> dpMapData1 = baseMapper.selectList(new QueryWrapper<DpMapData>().eq("select_type", "完成率"));
        List<DpMapData> saveList=new ArrayList<>();


        List<TrainPlanDetail> lhList=trainPlanDetailMapper.selectList(new QueryWrapper<TrainPlanDetail>().eq("disable",0)
                .eq("tally_flag",1).ge("zx_time", startDateTime).le("zx_time", endDateTime));
        List<TrainPlanDetail> formerLhList=trainPlanDetailMapper.selectList(new QueryWrapper<TrainPlanDetail>().eq("disable",0)
                .eq("tally_flag",1).ge("zx_time", formerStartDateTime).le("zx_time", formerEndDateTime));

        //保存完成率
        yearSum = saveRate(lhList, quarterSum, dpMapData, dpMapData1, saveList, yearSum, daySum, weekSum, monthSum);

        //保存 全年箱数
        saveCntrNum(yearSum);


        //保存客户发运到达箱 客户箱统计
        saveComNum(lhList, saveList);

        //集装箱吞吐量 月份
        saveTtMonthNum(lhList, saveList);

        //集装箱吞吐量 同比 环比
        saveAllTtMonthNum(lhList,formerLhList, saveList);

//        saveOrUpdateBatch(saveList);
    }

    private void saveAllTtMonthNum(List<TrainPlanDetail> lhList,List<TrainPlanDetail> formerLhList, List<DpMapData> saveList) {
        saveList=new ArrayList<>();
        List<DpMapData> cntrDatas = baseMapper.selectList(new QueryWrapper<DpMapData>().eq("select_type", "集装箱吞吐量同比环比"));

        for (int i = 1; i <= 12; i++) {
            Integer num=0;
            Integer lastNum=0;
            Integer hbNum=0;
            int h=i;
            List<TrainPlanDetail> list = lhList.stream().filter(s -> s.getZxTime().getMonthValue()==h).collect(Collectors.toList());
            List<TrainPlanDetail> lastList = formerLhList.stream().filter(s -> s.getZxTime().getMonthValue()==h).collect(Collectors.toList());
            //环比
            List<TrainPlanDetail> hbList=new ArrayList<>();
            if(h==1){
                hbList = formerLhList.stream().filter(s -> s.getZxTime().getMonthValue()==12).collect(Collectors.toList());
            }else{
                hbList = list.stream().filter(s -> s.getZxTime().getMonthValue()==(h-1)).collect(Collectors.toList());
            }

            if(list.size()>0){
                for (TrainPlanDetail trainPlanDetail : list) {
                    if(trainPlanDetail.getCntrSize().startsWith("2")){
                        num++;
                    }else{
                        num = num +2;
                    }
                }
            }
            if(lastList.size()>0){
                for (TrainPlanDetail trainPlanDetail : lastList) {
                    if(trainPlanDetail.getCntrSize().startsWith("2")){
                        lastNum++;
                    }else{
                        lastNum = lastNum +2;
                    }
                }
            }
            if(hbList.size()>0){
                for (TrainPlanDetail trainPlanDetail : hbList) {
                    if(trainPlanDetail.getCntrSize().startsWith("2")){
                        hbNum++;
                    }else{
                        hbNum = hbNum +2;
                    }
                }
            }

            DpMapData data=new DpMapData();
            if(cntrDatas.size()>0){
                DpMapData mapData = cntrDatas.stream().filter(s -> s.getName().equals(String.valueOf(h))).findFirst().get();
                BeanUtils.copyProperties(mapData,data);
            }
            data.setSelectType("集装箱吞吐量同比环比");
            data.setName(String.valueOf(h));
            data.setValue(String.valueOf(num));
            if(lastNum==0){
                data.setType("0%");
            }else{
                data.setType(new BigDecimal(num).multiply(new BigDecimal(100)).divide(new BigDecimal(lastNum),2,RoundingMode.HALF_UP).toString()+"%");//同比
            }
            if(hbNum==0){
                data.setMonth("0%");
            }else{
                data.setMonth(new BigDecimal(num).multiply(new BigDecimal(100)).divide(new BigDecimal(hbNum),2,RoundingMode.HALF_UP).toString()+"%");//环比
            }
            saveList.add(data);
        }
        saveOrUpdateBatch(saveList);
    }
    private void saveTtMonthNum(List<TrainPlanDetail> lhList, List<DpMapData> saveList) {
        saveList=new ArrayList<>();
        List<DpMapData> cntrDatas = baseMapper.selectList(new QueryWrapper<DpMapData>().eq("select_type", "集装箱吞吐量"));

        for (int i = 1; i <= 12; i++) {
            Integer xc=0;
            Integer zc=0;
            int h=i;
            List<TrainPlanDetail> xcList = lhList.stream().filter(s -> StringUtils.isNotEmpty(s.getSignLx()) && s.getZxTime().getMonthValue()==h).collect(Collectors.toList());
            List<TrainPlanDetail> zcList = lhList.stream().filter(s -> StringUtils.isEmpty(s.getSignLx()) && s.getZxTime().getMonthValue()==h).collect(Collectors.toList());
            if(xcList.size()>0){
                for (TrainPlanDetail trainPlanDetail : xcList) {
                    if(trainPlanDetail.getCntrSize().startsWith("2")){
                        xc++;
                    }else{
                        xc = xc +2;
                    }
                }
            }
            if(zcList.size()>0){
                for (TrainPlanDetail trainPlanDetail : zcList) {
                    if(trainPlanDetail.getCntrSize().startsWith("2")){
                        zc++;
                    }else{
                        zc = zc +2;
                    }
                }
            }
            DpMapData data=new DpMapData();
            if(cntrDatas.size()>0){
                DpMapData xcData1 = cntrDatas.stream().filter(s -> s.getType().equals("到达") && s.getName().equals(String.valueOf(h))).findFirst().get();
                BeanUtils.copyProperties(xcData1,data);
            }
            data.setSelectType("集装箱吞吐量");
            data.setName(String.valueOf(h));
            data.setValue(String.valueOf(xc));
            data.setType("到达");
            saveList.add(data);

            DpMapData data1=new DpMapData();
            if(cntrDatas.size()>0){
                DpMapData zcData1 = cntrDatas.stream().filter(s -> s.getType().equals("发运") && s.getName().equals(String.valueOf(h))).findFirst().get();
                BeanUtils.copyProperties(zcData1,data1);
            }
            data1.setSelectType("集装箱吞吐量");
            data1.setName(String.valueOf(h));
            data1.setValue(String.valueOf(zc));
            data1.setType("发运");
            saveList.add(data1);
        }
        saveOrUpdateBatch(saveList);
    }

    private void saveComNum(List<TrainPlanDetail> lhList, List<DpMapData> saveList) {
        saveList=new ArrayList<>();
        Map<String, List<TrainPlanDetail>> collect = lhList.stream().filter(s -> StringUtils.isNotEmpty(s.getConsignee())).collect(Collectors.groupingBy(TrainPlanDetail::getConsignee));
        // 按值（即数量）从大到小排序
        Comparator<Map.Entry<String, List<TrainPlanDetail>>> comparator =
                (entry1, entry2) -> Integer.compare(entry2.getValue().size(), entry1.getValue().size());

        List<Map.Entry<String, List<TrainPlanDetail>>> sortedEntries = collect.entrySet().stream()
                .sorted(comparator)
                .collect(Collectors.toList());

        List<DpMapData> cntrDatas = baseMapper.selectList(new QueryWrapper<DpMapData>().eq("select_type", "客户箱统计"));

        // 输出结果
        Integer i=0;
        Integer j=1;
        for (Map.Entry<String, List<TrainPlanDetail>> entry : sortedEntries) {
            if(i==6){
                break;
            }
            Integer xcSum=0;
            Integer zcSum=0;
            List<TrainPlanDetail> xcCntr = entry.getValue().stream().filter(s -> StringUtils.isNotEmpty(s.getSignLx())).collect(Collectors.toList());
            List<TrainPlanDetail> zcCntr = entry.getValue().stream().filter(s -> StringUtils.isEmpty(s.getSignLx())).collect(Collectors.toList());
            if(xcCntr.size()>0){
                for (TrainPlanDetail trainPlanDetail : xcCntr) {
                    if(trainPlanDetail.getCntrSize().startsWith("2")){
                        xcSum++;
                    }else{
                        xcSum = xcSum +2;
                    }
                }
            }
            if(zcCntr.size()>0){
                for (TrainPlanDetail trainPlanDetail : zcCntr) {
                    if(trainPlanDetail.getCntrSize().startsWith("2")){
                        zcSum++;
                    }else{
                        zcSum = zcSum +2;
                    }
                }
            }

            DpMapData comData=new DpMapData();
            if(cntrDatas.size()>0 && j<= cntrDatas.size()) {
                comData.setId(cntrDatas.get(cntrDatas.size()-j).getId());
            }
            comData.setSelectType("客户箱统计");
            comData.setName(entry.getKey());
            comData.setValue(String.valueOf(xcSum));
            comData.setType("到达");
            j++;

            DpMapData comData1=new DpMapData();
            if(cntrDatas.size()>0 && j<= cntrDatas.size()) {
                comData1.setId(cntrDatas.get(cntrDatas.size()-j).getId());
            }
            comData1.setSelectType("客户箱统计");
            comData1.setName(entry.getKey());
            comData1.setValue(String.valueOf(zcSum));
            comData1.setType("发运");
            saveList.add(comData);
            saveList.add(comData1);
            j++;
            i++;
        }
        saveOrUpdateBatch(saveList);
    }

    private void saveCntrNum(Integer yearSum) {
        DpMapData cntrData = baseMapper.selectOne(new QueryWrapper<DpMapData>().eq("select_type", "全年箱数"));
        DpMapData cntrData1=new DpMapData();
        if(cntrData !=null){
            BeanUtils.copyProperties(cntrData, cntrData1);
        }
        cntrData1.setSelectType("全年箱数");
        cntrData1.setName("全年箱数");
        cntrData1.setValue(String.valueOf(yearSum));
        cntrData1.setType("全年箱数");
        saveOrUpdate(cntrData1);
    }

    private Integer saveRate(List<TrainPlanDetail> lhList, Integer quarterSum, List<DpMapData> dpMapData, List<DpMapData> dpMapData1, List<DpMapData> saveList, Integer yearSum, Integer daySum, Integer weekSum, Integer monthSum) {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        int month = today.getMonthValue();

        //季度统计
        if (month >= 1 && month <= 3) {
            List<TrainPlanDetail> monthList = lhList.stream().filter(s -> s.getZxTime().getMonthValue() >= 1 && s.getZxTime().getMonthValue() <= 3).collect(Collectors.toList());
            if(monthList.size()>0){
                for (TrainPlanDetail trainPlanDetail : monthList) {
                    if(trainPlanDetail.getCntrSize().startsWith("2")){
                        quarterSum++;
                    }else{
                        quarterSum = quarterSum +2;
                    }
                }
            }
            DpMapData quarterData = dpMapData.stream().filter(s -> s.getType().equals("季度完成总量") && s.getName().equals("1")).findFirst().get();
            DpMapData data=new DpMapData();
            if(dpMapData1.size()>0){
                DpMapData data1 = dpMapData1.stream().filter(s -> s.getType().equals("季完成率")).findFirst().get();
                BeanUtils.copyProperties(data1,data);
            }
            data.setSelectType("完成率");
            data.setName("1");
            data.setValue(new BigDecimal(quarterSum).divide(new BigDecimal(quarterData.getValue()), 2, RoundingMode.HALF_UP).toString());
            data.setType("季完成率");
            saveList.add(data);
        } else if (month >= 4 && month <= 6) {
            List<TrainPlanDetail> monthList = lhList.stream().filter(s -> s.getZxTime().getMonthValue() >= 4 && s.getZxTime().getMonthValue() <= 6).collect(Collectors.toList());
            if(monthList.size()>0){
                for (TrainPlanDetail trainPlanDetail : monthList) {
                    if(trainPlanDetail.getCntrSize().startsWith("2")){
                        quarterSum++;
                    }else{
                        quarterSum = quarterSum +2;
                    }
                }
            }
            DpMapData quarterData = dpMapData.stream().filter(s -> s.getType().equals("季度完成总量") && s.getName().equals("2")).findFirst().get();
            DpMapData data=new DpMapData();
            if(dpMapData1.size()>0){
                DpMapData data1 = dpMapData1.stream().filter(s -> s.getType().equals("季完成率")).findFirst().get();
                BeanUtils.copyProperties(data1,data);
            }
            data.setSelectType("完成率");
            data.setName("2");
            data.setValue(new BigDecimal(quarterSum).divide(new BigDecimal(quarterData.getValue()), 2, RoundingMode.HALF_UP).toString());
            data.setType("季完成率");
            saveList.add(data);
        } else if (month >= 7 && month <= 9) {
            List<TrainPlanDetail> monthList = lhList.stream().filter(s -> s.getZxTime().getMonthValue() >= 7 && s.getZxTime().getMonthValue() <= 9).collect(Collectors.toList());
            if(monthList.size()>0){
                for (TrainPlanDetail trainPlanDetail : monthList) {
                    if(trainPlanDetail.getCntrSize().startsWith("2")){
                        quarterSum++;
                    }else{
                        quarterSum = quarterSum +2;
                    }
                }
            }
            DpMapData quarterData = dpMapData.stream().filter(s -> s.getType().equals("季度完成总量") && s.getName().equals("3")).findFirst().get();
            DpMapData data=new DpMapData();
            if(dpMapData1.size()>0){
                DpMapData data1 = dpMapData1.stream().filter(s -> s.getType().equals("季完成率")).findFirst().get();
                BeanUtils.copyProperties(data1,data);
            }
            data.setSelectType("完成率");
            data.setName("3");
            data.setValue(new BigDecimal(quarterSum).divide(new BigDecimal(quarterData.getValue()), 2, RoundingMode.HALF_UP).toString());
            data.setType("季完成率");
            saveList.add(data);
        } else {
            List<TrainPlanDetail> monthList = lhList.stream().filter(s -> s.getZxTime().getMonthValue() >= 10 && s.getZxTime().getMonthValue() <= 12).collect(Collectors.toList());
            if(monthList.size()>0){
                for (TrainPlanDetail trainPlanDetail : monthList) {
                    if(trainPlanDetail.getCntrSize().startsWith("2")){
                        quarterSum++;
                    }else{
                        quarterSum = quarterSum +2;
                    }
                }
            }
            DpMapData quarterData = dpMapData.stream().filter(s -> s.getType().equals("季度完成总量") && s.getName().equals("4")).findFirst().get();
            DpMapData data=new DpMapData();
            if(dpMapData1.size()>0){
                DpMapData data1 = dpMapData1.stream().filter(s -> s.getType().equals("季完成率")).findFirst().get();
                BeanUtils.copyProperties(data1,data);
            }
            data.setSelectType("完成率");
            data.setName("4");
            data.setValue(new BigDecimal(quarterSum).divide(new BigDecimal(quarterData.getValue()), 2, RoundingMode.HALF_UP).toString());
            data.setType("季完成率");
            saveList.add(data);
        }

        //年统计
        if(lhList.size()>0){
            for (TrainPlanDetail trainPlanDetail : lhList) {
                if(trainPlanDetail.getCntrSize().startsWith("2")){
                    yearSum++;
                }else{
                    yearSum = yearSum +2;
                }
            }
        }
        Optional<DpMapData> yearOp = dpMapData.stream().filter(s -> s.getType().equals("年完成总量") && s.getName().equals(String.valueOf(today.getYear()))).findFirst();
        DpMapData yearMapData=new DpMapData();
        if(yearOp.isPresent()){
            yearMapData=yearOp.get();
        }else{
            yearMapData.setName(String.valueOf(LocalDate.now().getYear()));
            yearMapData.setType("年完成总量");
            yearMapData.setSelectType("完成量");
            yearMapData.setValue("1000");
            save(yearMapData);
        }
        DpMapData data=new DpMapData();
        if(dpMapData1.size()>0){
            DpMapData data1 = dpMapData1.stream().filter(s -> s.getType().equals("年完成率")).findFirst().get();
            BeanUtils.copyProperties(data1,data);
        }
        data.setSelectType("完成率");
        data.setName(String.valueOf(today.getYear()));
        data.setValue(new BigDecimal(quarterSum).divide(new BigDecimal(yearMapData.getValue()), 2, RoundingMode.HALF_UP).toString());
        data.setType("年完成率");
        saveList.add(data);

        //每日统计
        List<TrainPlanDetail> dayList = lhList.stream().filter(s -> s.getZxTime().toLocalDate() == today).collect(Collectors.toList());
        if(dayList.size()>0){
            for (TrainPlanDetail trainPlanDetail : dayList) {
                if(trainPlanDetail.getCntrSize().startsWith("2")){
                    daySum++;
                }else{
                    daySum = daySum +2;
                }
            }
        }
        DpMapData dayData=new DpMapData();
        if(dpMapData1.size()>0){
            DpMapData data1 = dpMapData1.stream().filter(s -> s.getType().equals("今日完成量")).findFirst().get();
            BeanUtils.copyProperties(data1,dayData);
        }
        dayData.setSelectType("完成率");
        dayData.setName("今日完成量");
        dayData.setValue(daySum.toString());
        dayData.setType("今日完成量");
        saveList.add(dayData);

        //周统计
        // 获取本周的开始（周一）和结束（周日）的LocalDate
        LocalDate startOfWeek = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate endOfWeek = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));

        // 如果需要LocalDateTime，可以使用相同的时间部分
        LocalDateTime startWeekTime = LocalDateTime.of(startOfWeek, LocalDateTime.now().toLocalTime());
        LocalDateTime endWeekTime = LocalDateTime.of(endOfWeek, LocalTime.MAX);
        List<TrainPlanDetail> weekList=trainPlanDetailMapper.selectList(new QueryWrapper<TrainPlanDetail>().eq("disable",0)
                .eq("tally_flag",1).le("zx_time", startWeekTime).ge("zx_time", endWeekTime));
        if(weekList.size()>0){
            for (TrainPlanDetail trainPlanDetail : weekList) {
                if(trainPlanDetail.getCntrSize().startsWith("2")){
                    weekSum++;
                }else{
                    weekSum = weekSum +2;
                }
            }
        }

        DpMapData data1=new DpMapData();
        if(dpMapData1.size()>0){
            DpMapData data11 = dpMapData1.stream().filter(s -> s.getType().equals("本周完成量")).findFirst().get();
            BeanUtils.copyProperties(data11,data1);
        }
        data1.setSelectType("完成率");
        data1.setName("本周完成量");
        data1.setValue(weekSum.toString());
        data1.setType("本周完成量");
        saveList.add(data1);

        //月统计
        List<TrainPlanDetail> monthList = lhList.stream().filter(s -> s.getZxTime().getMonthValue() == month).collect(Collectors.toList());
        if(monthList.size()>0){
            for (TrainPlanDetail trainPlanDetail : monthList) {
                if(trainPlanDetail.getCntrSize().startsWith("2")){
                    monthSum++;
                }else{
                    monthSum = monthSum +2;
                }
            }
        }
        DpMapData monData1 = dpMapData.stream().filter(s -> s.getType().equals("月度完成总量") && s.getName().equals(String.valueOf(month))).findFirst().get();
        DpMapData monData=new DpMapData();
        if(dpMapData1.size()>0){
            DpMapData data11 = dpMapData1.stream().filter(s -> s.getType().equals("月完成率")).findFirst().get();
            BeanUtils.copyProperties(data11,monData);
        }
        monData.setSelectType("完成率");
        monData.setName(String.valueOf(month));
        monData.setValue(new BigDecimal(quarterSum).divide(new BigDecimal(monData1.getValue()), 2, RoundingMode.HALF_UP).toString());
        monData.setType("月完成率");
        saveList.add(monData);
        saveOrUpdateBatch(saveList);
        return yearSum;
    }

    @Override
    public void updateTrainPlanTotal() {
        // 获取当前年份的第一天和最后一天
        YearMonth currentYear = YearMonth.now();
        LocalDate startOfYear = currentYear.atDay(1);
        LocalDate endOfYear = currentYear.atDay(currentYear.lengthOfMonth());

        // 转换为 LocalDateTime，因为假设 zx_time 是 LocalDateTime 类型
        LocalDateTime startDateTime = startOfYear.atStartOfDay();
        LocalDateTime endDateTime = endOfYear.atTime(23, 59, 59, 999999999);

        List<TrainPlan> trainPlans=trainPlanMapper.selectList(new QueryWrapper<TrainPlan>().eq("disable",0)
               .le("create_time", startDateTime).ge("create_time", endDateTime));

        DpMapData dpMapData = baseMapper.selectOne(new QueryWrapper<DpMapData>().eq("select_type", "全年班列数"));
        DpMapData trainData=new DpMapData();
        if(dpMapData!=null){
            BeanUtils.copyProperties(dpMapData,trainData);
        }
        trainData.setSelectType("全年班列数");
        trainData.setName("全年班列数");
        trainData.setValue(String.valueOf(trainPlans.size()));
        trainData.setType("全年班列数");
        saveOrUpdate(trainData);
    }

    @Override
    public void updateYardCntrTotal() {
        List<CntrInfo> cntrInfos = cntrInfoMapper.selectList(new QueryWrapper<CntrInfo>().eq("disable", 0).eq("status", 0));
        List<DpMapData> dpMapDataList = baseMapper.selectList(new QueryWrapper<DpMapData>().eq("select_type", "在场箱统计"));
        List<DpMapData> list=new ArrayList<>();
        Integer fyNum=0;
        Integer ddNum=0;
        Integer eNum=0;
        Integer fNum=0;
        if(cntrInfos.size()>0){
            List<CntrInfo> fyList = cntrInfos.stream().filter(s -> StringUtils.isNotEmpty(s.getCntrWorkRemark())).collect(Collectors.toList());
            if(fyList.size()>0){
                fyNum=fyList.size();
            }
            List<CntrInfo> ddList = cntrInfos.stream().filter(s -> StringUtils.isNotEmpty(s.getCntrWorkRemarkB())).collect(Collectors.toList());
            if(ddList.size()>0){
                ddNum=ddList.size();
            }
            List<CntrInfo> eList = cntrInfos.stream().filter(s -> "E".equals(s.getEfFlag())).collect(Collectors.toList());
            if(eList.size()>0){
                eNum=eList.size();
            }
            List<CntrInfo> fList = cntrInfos.stream().filter(s -> "F".equals(s.getEfFlag())).collect(Collectors.toList());
            if(fList.size()>0){
                fNum=fList.size();
            }
        }
        DpMapData fyData=new DpMapData();
        if(dpMapDataList.size()>0){
            DpMapData data = dpMapDataList.stream().filter(s -> s.getName().equals("发运箱数") ).findFirst().get();
            BeanUtils.copyProperties(data,fyData);
        }
        fyData.setSelectType("在场箱统计");
        fyData.setName("发运箱数");
        fyData.setValue(new BigDecimal(fyNum).multiply(new BigDecimal(100)).divide(new BigDecimal(fyNum).add(new BigDecimal(ddNum)),2,RoundingMode.HALF_UP).toString()+"%");
        fyData.setMonth(String.valueOf(fyNum));
        list.add(fyData);

        DpMapData ddData=new DpMapData();
        if(dpMapDataList.size()>0){
            DpMapData data = dpMapDataList.stream().filter(s -> s.getName().equals("到达箱数") ).findFirst().get();
            BeanUtils.copyProperties(data,ddData);
        }
        ddData.setSelectType("在场箱统计");
        ddData.setName("到达箱数");
        ddData.setValue(new BigDecimal(ddNum).multiply(new BigDecimal(100)).divide(new BigDecimal(fyNum).add(new BigDecimal(ddNum)),2,RoundingMode.HALF_UP).toString()+"%");
        ddData.setMonth(String.valueOf(ddNum));
        list.add(ddData);

        DpMapData fData=new DpMapData();
        if(dpMapDataList.size()>0){
            DpMapData data = dpMapDataList.stream().filter(s -> s.getName().equals("重箱数") ).findFirst().get();
            BeanUtils.copyProperties(data,fData);
        }
        fData.setSelectType("在场箱统计");
        fData.setName("重箱数");
        fData.setValue(new BigDecimal(fNum).multiply(new BigDecimal(100)).divide(new BigDecimal(fNum).add(new BigDecimal(eNum)),2,RoundingMode.HALF_UP).toString()+"%");
        fData.setMonth(String.valueOf(fNum));
        list.add(fData);

        DpMapData eData=new DpMapData();
        if(dpMapDataList.size()>0){
            DpMapData data = dpMapDataList.stream().filter(s -> s.getName().equals("空箱数") ).findFirst().get();
            BeanUtils.copyProperties(data,eData);
        }
        eData.setSelectType("在场箱统计");
        eData.setName("空箱数");
        eData.setValue(new BigDecimal(eNum).multiply(new BigDecimal(100)).divide(new BigDecimal(fNum).add(new BigDecimal(eNum)),2,RoundingMode.HALF_UP).toString()+"%");
        eData.setMonth(String.valueOf(eNum));
        list.add(eData);
        saveOrUpdateBatch(list);
    }

    @Override
    public List<DpMapData> getDpMapData(DpMapData dpMapData) {
        QueryWrapper<DpMapData> queryWrapper=new QueryWrapper<>();
        if(StringUtils.isNotEmpty(dpMapData.getSelectType())){
            queryWrapper.eq("select_type",dpMapData.getSelectType());
            if("集装箱吞吐量".equals(dpMapData.getSelectType())){
                queryWrapper.last("limit 24");
            }
        }else{
            queryWrapper.isNull("select_type");
        }

        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public void updatePortTotal() {
        List<DpMapData> saveList=new ArrayList<>();
        List<TrainPlanDetailVo> list=trainPlanDetailMapper.selectPortList();
        List<TrainPlanDetail> lhList=new ArrayList<>();
        for (TrainPlanDetailVo trainPlanDetailVo : list) {
            TrainPlanDetail trainPlanDetail=new TrainPlanDetail();
            if(StringUtils.isEmpty(trainPlanDetailVo.getSignLx())){
                trainPlanDetailVo.setZhPort(trainPlanDetailVo.getEndPort());
            }
            BeanUtils.copyProperties(trainPlanDetailVo,trainPlanDetail);
            lhList.add(trainPlanDetail);
        }
        Map<String, List<TrainPlanDetail>> collect = lhList.stream().filter(s -> StringUtils.isNotEmpty(s.getZhPort())).collect(Collectors.groupingBy(TrainPlanDetail::getZhPort));
        // 按值（即数量）从大到小排序
        Comparator<Map.Entry<String, List<TrainPlanDetail>>> comparator =
                (entry1, entry2) -> Integer.compare(entry2.getValue().size(), entry1.getValue().size());

        List<Map.Entry<String, List<TrainPlanDetail>>> sortedEntries = collect.entrySet().stream()
                .sorted(comparator)
                .collect(Collectors.toList());

        List<DpMapData> cntrDatas = baseMapper.selectList(new QueryWrapper<DpMapData>().eq("select_type", "班列站点统计"));

        // 输出结果
        Integer i=0;
        Integer j=1;
        for (Map.Entry<String, List<TrainPlanDetail>> entry : sortedEntries) {
            if(i==6){
                break;
            }
            Integer xcSum=0;
            Integer zcSum=0;
            List<TrainPlanDetail> xcCntr = entry.getValue().stream().filter(s -> StringUtils.isNotEmpty(s.getSignLx())).collect(Collectors.toList());
            List<TrainPlanDetail> zcCntr = entry.getValue().stream().filter(s -> StringUtils.isEmpty(s.getSignLx())).collect(Collectors.toList());
            if(xcCntr.size()>0){
                for (TrainPlanDetail trainPlanDetail : xcCntr) {
                    if(trainPlanDetail.getCntrSize().startsWith("2")){
                        xcSum++;
                    }else{
                        xcSum = xcSum +2;
                    }
                }
            }
            if(zcCntr.size()>0){
                for (TrainPlanDetail trainPlanDetail : zcCntr) {
                    if(trainPlanDetail.getCntrSize().startsWith("2")){
                        zcSum++;
                    }else{
                        zcSum = zcSum +2;
                    }
                }
            }

            DpMapData comData=new DpMapData();
            if(cntrDatas.size()>0 && j<= cntrDatas.size()) {
                comData.setId(cntrDatas.get(cntrDatas.size()-j).getId());
            }
            comData.setSelectType("班列站点统计");
            comData.setName(entry.getKey());
            comData.setValue(String.valueOf(xcSum));
            comData.setType("到达");
            j++;

            DpMapData comData1=new DpMapData();
            if(cntrDatas.size()>0 && j<= cntrDatas.size()) {
                comData1.setId(cntrDatas.get(cntrDatas.size()-j).getId());
            }
            comData1.setSelectType("班列站点统计");
            comData1.setName(entry.getKey());
            comData1.setValue(String.valueOf(zcSum));
            comData1.setType("发运");
            saveList.add(comData);
            saveList.add(comData1);
            j++;
            i++;
        }
        saveOrUpdateBatch(saveList);
    }


}
